import DlyadminAiFuncsConfig from '../../model/dlyadminAiFuncsConfig'

import ApiError from '../../error/ApiError'
import ApiErrorNames from '../../error/ApiErrorNames'
import AiOrder from '../../model/AiOrder'

class AiFuncsConfig {
	static async list(ctx) {
		// 获取列表全部数据
		const { status } = ctx.request.query || {}
		const getTapol = {
			status: status ? status : ''
		}
		for (let key in getTapol) {
			if (getTapol[key] == '') {
				delete getTapol[key]
			}
		}
		const result = await DlyadminAiFuncsConfig.find(getTapol)
		.sort({ createTime: -1 })
		.limit(1000).skip(0)
		const total = await DlyadminAiFuncsConfig.find(getTapol).countDocuments()
		return ctx.body = { list: result, total }
	}
	static async add(ctx) {
		console.log('ctx.request.body', ctx.request.body)
		const {
			type = '',
			name = '',
			status = '',
			num = '',
			charge = '',
			similarCharge = '',
			linenum=''
		} = ctx.request.body || {}
		if (!name || !type || !num || !charge || !similarCharge || !linenum) {
			// 缺少必要参数
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		const addData = {
			type,
			name,
			status,
			num,
			charge,
			similarCharge,
			linenum
		}
		for (let key in addData) {
			if (addData[key] == '') {
				delete addData[key]
			}
		}
		const getFindData = await DlyadminAiFuncsConfig.findOne({ type: addData.type })
		if (getFindData) {
			throw new ApiError(ApiErrorNames.ADD_ISINFOTER)
		}
		const result = await DlyadminAiFuncsConfig.create(addData)
		if (result) {
			return ctx.body = '添加成功'
		}
		throw new ApiError(ApiErrorNames.ADD_GOODS_FAIL)
	}
	static async edit(ctx) {
		// 编辑列表
		const id = ctx.params.id
		if (!id) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		const {
			type = '',
			name = '',
			status = '',
			num = '',
			charge = '',
			similarCharge = '',
			linenum = ''
		} = ctx.request.body || {}
		if (!name || !type || !num || !charge || !similarCharge || !linenum) {
			// 缺少必要参数
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		const editData = {
			type,
			name,
			status,
			num,
			charge,
			similarCharge,
			linenum
		}
		for (let key in editData) {
			if (editData[key] == '') {
				delete editData[key]
			}
		}

		const result = await DlyadminAiFuncsConfig.updateOne({ _id: id }, editData)
		if (result.nModified === 0) {
			throw new ApiError(ApiErrorNames.NoData)
		}
		return ctx.body = '修改成功'
	}
	static async deleted(ctx) {
		const id = ctx.params.id
		if (!id) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		try {

			const result = await DlyadminAiFuncsConfig.deleteOne({ _id: id })
			if (result.deletedCount === 0) {
				throw new ApiError(ApiErrorNames.NoData)
			}
			// upDataWhiteList()
			ctx.body = 'ok'
		} catch (error) {
			throw new ApiError(ApiErrorNames.UnknownError)
		}
	}
}

export default AiFuncsConfig
